package com.zhm.demo.utils;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.PathContainer;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class UrlUtil {
    private static final PathPatternParser parser = new PathPatternParser();

    public static boolean checkPathMatch(String pattern, String url) {
        PathPattern pathPattern = parser.parse(pattern);
        return pathPattern.matches(PathContainer.parsePath(url));
    }

    private static final PathPatternParser pathPatternParser = new PathPatternParser();

    /**
     * 完整URI解析
     *
     * @param fullUri 完整URI（支持带协议头的绝对路径）
     * @param pattern 路由规则（如"/api/{version}/users/{id}"）
     * @return 结构化解析结果
     */
    public static UriParseResult parse(String fullUri, String pattern) {
        // 标准化URI处理
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(fullUri).build().normalize();

        // 路径参数解析
        PathPattern pathPattern = pathPatternParser.parse(pattern);
        PathContainer pathContainer = PathContainer.parsePath(uriComponents.getPath());

        boolean isMatch = pathPattern.matches(pathContainer);
        Map<String, String> pathVariables = isMatch ?
                pathPattern.matchAndExtract(pathContainer).getUriVariables() :
                Collections.emptyMap();

        // 查询参数结构化处理
        Map<String, List<String>> queryParams = uriComponents.getQueryParams()
                .entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        e -> List.copyOf(e.getValue())
                ));


        return new UriParseResult(
                uriComponents.getScheme(),
                uriComponents.getUserInfo(),
                uriComponents.getHost(),
                uriComponents.getPort(),
                uriComponents.getPath(),
                queryParams,
                pathVariables,
                uriComponents.getFragment(),
                isMatch
        );
    }

    @Data
    public static class UriParseResult {
        private final String scheme;
        private final String userInfo;
        private final String host;
        private final int port;
        private final String path;
        private final Map<String, List<String>> queryParams;
        private final Map<String, String> pathVariables;
        private final String fragment;
        private final boolean matched;

        // 构造方法、Getter省略
    }

    public static void main(String[] args) throws Exception {
        UriParseResult parse = parse("https://zhm:pass@zhm.com/a/78/12?w=45&e=kk#index", "/a/{b}/12");
        System.out.println(parse);
        URI uri = new URI("https://zhm:pass@zhm.com/a/78/12?w=45&e=kk#index");
        System.out.println(uri.getScheme());
        System.out.println(uri.getUserInfo());
        System.out.println(uri.getHost());
        System.out.println(uri.getPort());
        System.out.println(uri.getPath());
        System.out.println(uri.getQuery());
        System.out.println(uri.getFragment());


        System.out.println("----------------");
        System.out.println(checkPathMatch("/a/{b}/12", "/a/78/12"));
        System.out.println("----------------");
    }
}
